#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "http.h"

void MainWindow::weather_init()
{
    weather_timer->setInterval(3600000); //one hour
    connect(weather_timer, &QTimer::timeout, this,
            &MainWindow::weather_update);
    weather_timer->start();//每小时update一次
    weather_update();       //初始化update一次
    qDebug() << "weather init done.";
}

void MainWindow::weather_update()
{
    Http *http = new Http(settings->value("SmartCT/get_weather_url").toString(), Http::GET);
    connect(http->getAccessManager(), &QNetworkAccessManager::finished,
            this, &MainWindow::weather_update_callback);
    http->send();
    qDebug() << "weather update http send.";
}

void MainWindow::weather_update_display(weather_info w_info)
{
    QString info_string = QString("温度：%1℃\n"
                                  "湿度：%2%\n"
                                  "体感温度：%3℃\n"
                                  "空气质量：%4\n"
                                  "%5  %6\n")
            .arg(w_info.sk_t)
            .arg(w_info.sk_h)
            .arg(w_info.sk_t_feel)
            .arg(w_info.pm_q)
            .arg(w_info.sk_w).arg(w_info.now_summary1);
    ui->label_weather->setText(info_string);
}

void MainWindow::weather_update_callback(QNetworkReply *reply)
{
    qDebug() << "weather_update_callback.";
    QJsonObject jsonObject = Http::checkHttpResponseError(reply);
    if(jsonObject.isEmpty())
    {
        qCritical() << "天气数据响应错误";
        return;
    }
/*
 * typedef struct weather_info {
        double sk_t;             //17.3
        QString sk_s;           //阴
        double sk_t_feel;        //体感温度
        QString now_summary1;   //建议
        QString ln_dt;          //农历日期
        QString pm_q;           //空气质量
        QString sk_w;           //东风2级
        int sk_h;               //湿度%
    }weather_info;
*/

    weather_data.sk_t = jsonObject.value("rows").toArray()
            .at(0).toObject().value("sk_t").toString().toDouble();
    weather_data.sk_h = jsonObject.value("rows").toArray()
            .at(0).toObject().value("sk_h").toInt();
    weather_data.sk_s = jsonObject.value("rows").toArray()
            .at(0).toObject().value("sk_s").toString();
    weather_data.sk_t_feel = jsonObject.value("rows").toArray()
            .at(0).toObject().value("sk_t_feel").toString().toDouble();
    weather_data.now_summary1 = jsonObject.value("now_summary1").toString();
    weather_data.ln_dt = jsonObject.value("ln_dt").toString();
    weather_data.pm_q = jsonObject.value("rows").toArray()
            .at(0).toObject().value("pm_q").toString();
    weather_data.sk_w = jsonObject.value("rows").toArray()
            .at(0).toObject().value("sk_w").toString();
    weather_update_display(weather_data);//联网更新之后更新屏幕信息
}
